package com.ebelter.btcomlib.utils.log;

import android.content.Context;
import android.os.Environment;
import com.ebelter.btcomlib.CommonLib;
import org.apache.log4j.Level;
import java.io.File;

import de.mindpipe.android.logging.log4j.LogConfigurator;


public class Log4jConfigure {
    private static final String TAG = "Log4jConfigure";

    private static final int MAX_FILE_SIZE = 1024 * 1024 * 3;//log文件的大小
    private static final String DEFAULT_LOG_DIR = "/BtProducts/Log";
    private static final String DEFAULT_LOG_FILE_NAME = "app.log";

    // 对应AndroidManifest文件中的package
  //  private static final String PACKAGE_NAME = "com.ebelter.temperaturestick";

    private static void configure(Context context,String fileName) {
        final LogConfigurator logConfigurator = new LogConfigurator();
        try {
           // /storage/emulated/0/MySimples/Log/app.log
            String logfileName;

            if (isSdcardMounted()) {
                logfileName=Environment.getExternalStorageDirectory() + DEFAULT_LOG_DIR + fileName;
            } else {
                logfileName="//data//data//" + context.getPackageName() + "//files"+ File.separator + fileName;
            }
            File file=new File(logfileName);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()){
                boolean s=parentFile.mkdirs();
                android.util.Log.i(TAG, logfileName+"父类不存在1,创建父类="+s);
            }

            if (!file.exists()){
                boolean cF=file.createNewFile();
                android.util.Log.i(TAG, logfileName+"文件不存在,创建文件1="+cF);
            }

            logConfigurator.setFileName(logfileName);
            //以下设置是按指定大小来生成新的文件

            logConfigurator.setMaxBackupSize(3);
            logConfigurator.setMaxFileSize(MAX_FILE_SIZE);


            //以下设置是按天生成新的日志文件,与以上两句互斥,MAX_FILE_SIZE将不在起作用
            //文件名形如 MyApp.log.2016-06-02,MyApp.log.2016-06-03
            //logConfigurator.setUseDailyRollingFileAppender(true);

            //以下为通用配置
            logConfigurator.setImmediateFlush(true);
            logConfigurator.setRootLevel(Level.DEBUG);
            logConfigurator.setFilePattern("%d\t%p/%c:\t%m%n");
            logConfigurator.configure();
            android.util.Log.i(TAG, "Log4j config finish");
        } catch (Throwable throwable) {
            logConfigurator.setResetConfiguration(true);
            android.util.Log.e(TAG, "Log4j config error, use default config. Error:" + throwable);
        }
    }

    public static void configure() {
        configure(CommonLib.APPContext,DEFAULT_LOG_FILE_NAME);
    }

    private static boolean isSdcardMounted() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }
}

